package com.lhyl.front.web.shiro.mapper;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.shiro.cache.AbstractCacheManager;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.MapCache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.lhyl.front.constant.UserConstant;
import com.lhyl.front.web.controller.BaseController;
import com.lhyl.front.web.shiro.service.UserService;

public class UserSessionManager extends CachingSessionDAO
{
    
    @Autowired
    public UserService userService;

    public UserSessionManager()
    {
        setCacheManager(new AbstractCacheManager()
        {
            @Override
            protected Cache<Serializable, Session> createCache(String name) throws CacheException
            {
                return new MapCache<Serializable, Session>(name, new ConcurrentHashMap<Serializable, Session>());
            }
        });
    }

    protected Serializable doCreate(Session session)
    {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        return sessionId;
    }

    protected Session doReadSession(Serializable sessionId)
    {
        String loginUserName = BaseController.getCurrentUsername();
        
        // 当前用户是否已经登陆
        if (!StringUtils.isEmpty(loginUserName))
        {
            userService.setUserLine(loginUserName, UserConstant.LINE);
        }
        
        return null; // should never execute because this implementation relies
                     // on parent class to access cache, which
        // is where all sessions reside - it is the cache implementation that
        // determines if the
        // cache is memory only or disk-persistent, etc.
    }

    protected void doUpdate(Session session)
    {
        // does nothing - parent class persists to cache.
    }

    protected void doDelete(Session session)
    {
        if (null != session)
        {
            try
            {
                Object userName = session
                        .getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
                if (!StringUtils.isEmpty(userName))
                {

                    userService.setUserLine(userName.toString(), UserConstant.ON_LINE);
                }
            }
            catch (Exception e)
            {
                System.err.println(e.getMessage());
            }
        }
    }
}
